package memleak.test.com.testlist;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;



import java.util.List;

/**
 * Created by runrun on 2017/2/13.
 */

public class TabViewPager extends ViewPager implements IA {
    private static final String TAG = "TabViewPager";
    private TabAdapter mTabAdapter;
    private OnTabChannelListener mOnTabChannelListener;
    private OnPageLayoutListener mOnPageLayoutListener;

    private PreferencesDataSource mPreferencesDataSource;


    private ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (View.VISIBLE != getVisibility()) {
                return;
            }
            int count = getChildCount();
            if (0 == count) {
                return;
            }
            getViewTreeObserver().removeOnGlobalLayoutListener(this);
            int currentItem = getCurrentItem();
            if (null != mOnPageLayoutListener) {
                mOnPageLayoutListener.onLayoutOver();
            }
            if (null != mOnTabChannelListener) {
                mOnTabChannelListener.onTabSelected(mTabAdapter.getChannelCategory(currentItem));
            }


            ChannelLayout child = (ChannelLayout) findViewWithTag(getCurrentItem());
            if (null == child) {
                return;
            }
            child.initFocus(); //first play location

        }
    };
    private OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (null == mOnTabChannelListener) {
                return;
            }
            mOnTabChannelListener.onTabSelected(mTabAdapter.getChannelCategory(position));
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    public TabViewPager(Context context) {
        this(context, null);
    }

    public TabViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() != KeyEvent.ACTION_DOWN) {
            return super.dispatchKeyEvent(event);
        }
        int keyCode = event.getKeyCode();
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_RIGHT: {
                if (isInPageRightmost()) {
                    setCurrentItem(0);
                    return true;
                }
                break;
            }
            case KeyEvent.KEYCODE_DPAD_LEFT: {
                if (isInPageLeftmost()) {
                    setCurrentItem(mTabAdapter.getCount() - 1);
                    return true;
                }
                break;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    private boolean isInPageRightmost() {
        return getCurrentItem() == mTabAdapter.getCount() - 1;
    }

    private boolean isInPageLeftmost() {
        return getCurrentItem() == 0;
    }

    public void showCurrentChannel(int channelPos) {
        View view = findViewWithTag(getCurrentItem());
        if (null == view) {
            return;
        }
        final ChannelLayout layout = (ChannelLayout) view;
        layout.setCurrentItem(channelPos);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        setup();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        destroy();
    }

    @Override
    public void setup() {
        addOnPageChangeListener(mOnPageChangeListener);
        getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
    }

    @Override
    public void destroy() {
        removeOnPageChangeListener(mOnPageChangeListener);
        getViewTreeObserver().removeOnGlobalLayoutListener(mOnGlobalLayoutListener);
    }

    private void init() {
        mTabAdapter = new TabAdapter();
        setAdapter(mTabAdapter);
    }

    public void setOnPageLayoutListener(OnPageLayoutListener listener) {
        mOnPageLayoutListener = listener;
    }

    public void setTabChannelListener(OnTabChannelListener listener) {
        mOnTabChannelListener = listener;
    }


    public void selectChannelByNumber(int logicNum) {
        View view = getChildAt(getCurrentItem());
        if (null == view) {
            return;
        }
        ((ChannelLayout) view).selectItemByNumber(logicNum);
    }

    public LiveChannel getChannelByNumber(int logicNum) {
        View view = findViewWithTag(getCurrentItem());
        if (null == view) {
            return null;
        }
        return ((ChannelLayout) view).getItemByNumber(logicNum);
    }

    public int findPagebyId(String id) {
        int count = mTabAdapter.getCount();
        for (int i = 0; i < count; i++) {
            if (id.equals(mTabAdapter.getChannelCategory(i).getCategoryID())) {
                return i;
            }
        }
        return -1;
    }

    public void updateView(List<ChannelCategory> channelCategories) {
        if (null == channelCategories || channelCategories.isEmpty()) {
            return;
        }
        ViewTreeObserver observer = getViewTreeObserver();
        observer.removeOnGlobalLayoutListener(mOnGlobalLayoutListener);
        observer.addOnGlobalLayoutListener(mOnGlobalLayoutListener);
        mTabAdapter.updateData(channelCategories);
        mTabAdapter.notifyDataSetChanged();
        if (mPreferencesDataSource == null) {
            mPreferencesDataSource = PreferencesDataSource.newInstance();
        }
        int index = 0;
        String categoryName = mPreferencesDataSource.getPreChannelCategoryID();
        int cno = mPreferencesDataSource.getPreChannelNum();
        Log.i(TAG, "保存的频道分类是: " + categoryName + " ; 保存的频道是: " + cno);
        for (int i = 0; i < channelCategories.size(); i++) {
            String categoryID = channelCategories.get(i).getCategoryID();
            if (categoryName.equals(categoryID)) {
                index = i;
                LiveApplication app = (LiveApplication) getContext().getApplicationContext();
                app.changePagePos(index);
                break;
            }
        }
        Log.i(TAG, "INDEX = " + index);
        setCurrentItem(index, false);
    }

    /**
     * 获取当前页面数 因为getChildCount不准
     *
     * @return
     */
    public int getPagesCounts() {
        return mTabAdapter.getCount();
    }

    /**
     * 更新单个page的数据
     *
     * @param channelCategory
     */
    public void updateSinglePage(ChannelCategory channelCategory) {
        if (null == channelCategory) {
            return;
        }
        String channelCategoryID = channelCategory.getCategoryID();
        Log.i("fuping", "channelCategoryID == " + channelCategoryID);
        if (TextUtils.isEmpty(channelCategoryID)) {
            return;
        }
        int count = getChildCount();
        ChannelLayout child;
        for (int i = 0; i < count; i++) {


            child = (ChannelLayout) getChildAt(i);
            if (!channelCategoryID.equals(child.getCategoryID())) {
                continue;
            }
            child.updateView(channelCategory.getLiveChannels());
        }


    }



    public void updateFavoritesOnPagerAdapter(LiveChannel channel){
        mTabAdapter.updateFavorites(channel);
    }


    public String getCurCategoryId() {

        ChannelCategory cc =  mTabAdapter.getChannelCategory(getCurrentItem());
        if( cc == null ){
            return  "";
        }else{
            return cc.getCategoryID();
        }

    }

    public String getPreCategoryId(){
        if(getCurrentItem() - 1 < 0 || mTabAdapter.getChannelCategory(getCurrentItem()-1) == null){
            return null;
        }
        return mTabAdapter.getChannelCategory(getCurrentItem()-1).getCategoryID();
    }

    public String getNextCategoryId(){
        if(getCurrentItem() + 1 >= mTabAdapter.getCount() || mTabAdapter.getChannelCategory(getCurrentItem()+1) == null){
            return null;
        }
        return mTabAdapter.getChannelCategory(getCurrentItem()+1).getCategoryID();
    }


    public interface OnPageLayoutListener {
        void onLayoutOver();
    }
}
